<?php
/**
 * 公共设置
 */

use app\config\Alioss;
use app\config\Db;
use app\config\Sms;
use app\config\ImgCode;
use Core\Result\Result;
use Core\Common\Common;
use app\config\Redis;
use Core\Utils\Utils;

/**
 * 短信验证码 TODO
 * @return void
 */
function smsCode($data)
{
    $mobile = $data["mobile"];
    $type = $data["type"];
    $db = new Db();
    if (empty($mobile)) {
        $user_id = Common::getUser_id($data);
        if (empty($user_id)) Result::error("你还未登录，请登录后操作！");
        $userInfoSql = "select ui.mobile from user_info where user_id={$user_id} limit 1";
        $userInfo = $db->find($userInfoSql);
        if (empty($userInfo)) Result::error("账户不存在");
        if (!empty($userInfo['mobile'])) $mobile = $userInfo['mobile'];
    }
    switch ($type){
        case 1 : $smsType = 'sms_code_';break;//注册
        case 2 : $smsType = 'sms_code_login_';break;//登录
        case 3 : $smsType = 'sms_fpd_login_';break;//忘记密码
        case 4 : $smsType = 'sms_tra_login_';break;//重置交易密码
        case 5 : $smsType = 'zxsms_code_';break;//注销
        default:$smsType = 'sms_code_';break;//注册
    }
    $sendMobile = str_replace(' ', '', $mobile);;
    if (!Utils::phoneChecking($mobile)) Result::error("非法手机号");
    $cache = new Redis();
    if (!$cache->get("$smsType{$sendMobile}")) {
        $sms = new Sms();
        $length = 6;
        $code = str_pad(mt_rand(0, pow(10, $length) - 1), $length, '0', STR_PAD_LEFT);
        $sms->captcha($mobile, $code);
        $cache->setEx("$smsType{$sendMobile}", 60 * 5, $code);
    }
    Result::success("短信发送成功");
}

/**
 * 图片验证码 TODO
 * @return void
 */
function imgCode()
{
    $imgCode = ImgCode::create(1);
    Result::success($imgCode);
}

/**
 * 客服端上传图片 TODO
 * @param $data $_FILES
 * @return void
 * @throws \think\Exception
 */
function uploadImgs($data)
{
    $type = $data['type'];
    $file = $_FILES['file'];
    if (!isset($file)) {
        Result::error("请上传文件");
    }
    $imgType = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
    $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    if (!in_array($ext, $imgType)) {
        Result::error("不支持文件类型，文件类型错误！");
    }
    $file_size = number_format(($file['size'] / 1024 / 1024), 2); //MB
    if ($file_size > 5) {
        Result::error("文件超出限定大小5M");
    }
    switch ($type) {
        case 1://头像
            $saveName = 'header-img/';
            break;
        case 2://评价
            $saveName = 'evaluate-img/';
            break;
        case 3://售后
            $saveName = 'aftersales-img/';
            break;
        default:
            Result::error("非法请求类型");
    }

    $saveName .= date('YmdHis') . rand(10001, 99999) . '.' . $ext;
    $oss = new Alioss();
    $imgInfo = $oss->ossUpload($file['tmp_name'], $saveName);
    $secureUrl = str_replace('http://', 'https://', $imgInfo['oss-request-url']);
    Result::success(['img_url' => $secureUrl]);
}

/**
 * 文件上传 TODO
 *
 * @param array $param 文件信息
 *
 * @return array|Exception
 */
//function uploadFile()
//{
//    global $db, $hostDb, $time, $datetime;
//    $设置信息 = $db->find("select * from kuaibu_file_setting where setting_id=1 limit 1");
//    if ($设置信息['is_open'] == 0) returnData(500, '文件上传未开启，无法上传文件！');
//    $file = $_FILES['file'];
//
//    $param['file_name'] = pathinfo($file['name'], PATHINFO_FILENAME);
//    $file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
//    $file_type = getFileType($file_ext);
//    $file_size = $file['size'];
//    $file_md5 = md5($param['file_name']);
//    $file_hash = sha1($param['file_name']);
//    $file_name = 'file/' . date('Ymd') . '/' . $file_hash . ".$file_ext";
//    if (!in_array($file_ext, explode(',', $设置信息['image_ext']))) returnData(500, "非法文件上传类型，仅支持{$设置信息['image_ext']}格式上传");
//    if (round($file_size / 1024 / 1024, 2) > $设置信息['image_size']) returnData(500, "文件上传超限，最大可上传{$设置信息['image_size']}M");
//
//    $param['file_name'] = pathinfo($file['name'], PATHINFO_FILENAME);
//    $param['file_md5'] = $file_md5;
//    $param['file_hash'] = $file_hash;
//    $param['file_path'] = 'storage/' . $file_name;
//    $param['file_ext'] = $file_ext;
//    $param['file_size'] = $file_size;
//    $param['file_type'] = $file_type;
//    $param['storage'] = 'aliyun';
//    $param['is_front'] = 1;
//    $param['create_time'] = $datetime;
//    $param['update_time'] = $datetime;
//    if (empty($param['file_name'])) {
//        $param['file_name'] = create_order_no('scaled_image_picker');
//    }
//
//    // 对象存储
//    $oss = new Alioss();
//    $上传阿里云信息 = $oss->ossUpload($file['tmp_name'], $param['file_path']);
//    $param['domain'] = $上传阿里云信息['oss-requestheaders']['Host'];
//    $组装新增数据 = insertSql('ysmz_file', $param);
//    if (!$hostDb->save($组装新增数据)) returnData(500, '文件写入失败');
//    $param['file_id'] = $hostDb->find("SELECT LAST_INSERT_ID() as file_id")['file_id'];
//    $param['img_url'] = $上传阿里云信息['oss-request-url'];
//    returnData(200, '成功', $param);
//}

/**
 * 文件类型获取 TODO
 *
 * @param string $file_ext 文件后缀
 *
 * @return string image图片，video视频，audio音频，word文档，other其它
 */
function getFileType($file_ext = '')
{
    if ($file_ext) {
        $file_ext = strtolower($file_ext);
    }

    $image_ext = [
        'jpg', 'png', 'jpeg', 'gif', 'bmp', 'webp', 'ico', 'svg', 'tif', 'pcx', 'tga', 'exif',
        'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'wmf', 'avif', 'apng', 'xbm', 'fpx'
    ];
    $video_ext = [
        'mp4', 'avi', 'mkv', 'flv', 'rm', 'rmvb', 'webm', '3gp', 'mpeg', 'mpg', 'dat', 'asx', 'wmv',
        'mov', 'm4a', 'ogm', 'vob'
    ];
    $audio_ext = [
        'mp3', 'aac', 'wma', 'wav', 'ape', 'flac', 'ogg', 'adt', 'adts', 'cda', 'cd', 'wave',
        'aiff', 'midi', 'ra', 'rmx', 'vqf', 'amr'
    ];
    $word_ext = [
        'doc', 'docx', 'docm', 'dotx', 'dotm', 'txt',
        'xls', 'xlsx', 'xlsm', 'xltx', 'xltm', 'xlsb', 'xlam', 'csv',
        'ppt', 'pptx', 'potx', 'potm', 'ppam', 'ppsx', 'ppsm', 'sldx', 'sldm', 'thmx'
    ];

    if (in_array($file_ext, $image_ext)) {
        return 'image';
    } elseif (in_array($file_ext, $video_ext)) {
        return 'video';
    } elseif (in_array($file_ext, $audio_ext)) {
        return 'audio';
    } elseif (in_array($file_ext, $word_ext)) {
        return 'word';
    } else {
        return 'other';
    }
}

/**
 * 地区信息
 * @return void
 */
function region($data)
{
    $isTree = $data["isTree"];
    $type = $data["type"];
    $region_name = $data["regionName"];
    $isTree = $isTree ?? 1;
    $type = $type ?? 1;
    $field = "region_id,region_pid,region_name,region_pinyin,region_citycode,region_zipcode,region_longitude,region_latitude,region_sort";
    $cache = new Redis();
    $db = new Db();
    if ($type == 1) {//获取全部
        $地区信息 = unserialize($cache->get("region{$isTree}"));
        if (!$地区信息) {
            $地区信息 = $db->query("select $field from ysmz_region where is_delete=0 order by region_sort desc,region_id asc");
            if ($isTree == 1) $地区信息 = list_to_tree($地区信息, 'region_id', 'region_pid');
            $cache->setEx("region{$isTree}", 60 * 60 * 30, serialize($地区信息));
        }
    }
    if ($type == 2) {//获取详情
        $地区信息 = $db->find("select $field from `ysmz_region` where region_name='$region_name' and is_delete=0");
    }
    Result::success($地区信息);
}